package org.particlethink.mapper.impl;

import org.particlethink.config.RequestConfig;
import org.particlethink.context.Context;
import org.particlethink.entry.MaterialCategory;
import org.particlethink.mapper.CategoryMapper;
import org.particlethink.model.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Repository
@ConditionalOnExpression("#{!'dev'.equals('${spring.profiles.active}')}")
public class ProCategoryMapperImpl implements CategoryMapper {

    @Autowired
    private RequestConfig requestConfig;

    @Override
    public List<Category> selectByIds(String token, List<String> ids) {
        return all(token).stream().filter(category -> ids.contains(category.getId())).collect(Collectors.toList());
    }

    @Override
    public List<Category> selectByParentId(String token, String parentId) {
        return all(token).stream().filter(category -> category.getParentID().equals(parentId)).collect(Collectors.toList());
    }

    @Override
    public List<Category> selectParents(String token) {
        return all(token).stream().filter(category -> category.getLevel() == MaterialCategory.PARENT_CATEGORY).collect(Collectors.toList());
    }

    @Override
    public Category selectById(String token, String id) {
        return all(token).stream().filter(category -> category.getId().equals(id)).findFirst().orElse(null);
    }

    @Override
    public List<Category> all(String token) {
        List<Category> categories = new ArrayList<>();
        try {
            List<ProMaterialRequestHelper.MajorType> majorTypes = ProMaterialRequestHelper.listMajorTypes(requestConfig.getUrl(), token);
            majorTypes.forEach(majorType -> {
                categories.add(new Category(majorType.getMajorCode(), null, null, majorType.getMajorName(), "", MaterialCategory.PARENT_CATEGORY));
                majorType.getMinorType().forEach(minorType -> {
                    categories.add(new Category(minorType.getMinorCode(), null, null, minorType.getMinorName(), majorType.getMajorName(), MaterialCategory.CATEGORY));
                });
            });
        } catch (URISyntaxException | IOException e) {
            throw new RuntimeException(e);
        }
        return categories;
    }

    @Override
    public List<Category> findByName(String token, String name) {
        return all(token).stream().filter(category -> category.getName().contains(name)).collect(Collectors.toList());
    }
}
